package com.chenjun.parse;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.chenjun.request.HttpClientMethod;
import com.chenjun.utils.FileUtils;

public class DownLoadFile
{
	public String getHttpFileNameByUrl(String url)
	{
		url = url.substring("http://".length());
		url = deleteLastSlash(url);
		if (url.endsWith(".html") 
				|| url.endsWith(".com") 
				|| url.endsWith(".cn")
				|| url.endsWith(".top")
				|| url.endsWith(".org")
				|| url.endsWith(".info")
				|| url.endsWith(".wang")
				|| url.endsWith(".cc")
				|| url.endsWith(".io"))
		{
			url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
			return url;
		}
		else
		{
			return "NULL";
		}
	}

	public void saveToLocal(String httpResponseStr, String filePath)
	{
		try
		{
			File file = new File(filePath);
			FileUtils.createFile(file);
			FileUtils.writeFile(filePath, httpResponseStr);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 下载网页
	 */
	public String downLoadFile(String url, int timeOutValue)
	{
		String filePath = null;
		String httpResponseStr = null;
		HttpClientMethod httpClientMethod = new HttpClientMethod();
		httpClientMethod.setUrlPath(url);
		httpClientMethod.setTimeOutValue(timeOutValue);
		httpResponseStr = httpClientMethod.httpGetMethod(url);
		filePath = "c://javadownLoad//" + getHttpFileNameByUrl(url);
		if(StringUtils.isNotBlank(httpResponseStr))
		{
			saveToLocal(httpResponseStr, filePath);
			System.out.println("【"+filePath+"】 is succeeded download");
		}
		else
		{
			System.out.println("该网站设置了防爬取处理");
		}
		return httpResponseStr;
	}
	
	/**
	 * 去掉网址末尾的斜杠
	 */
	public String deleteLastSlash(String url)
	{
		String afterUrl = null;
		while(true)
		{
			if(url.endsWith("/"))
			{
				url = url.substring(0, url.length()-1);
			}
			else
			{
				afterUrl = url;
				break;
			}
		}
		return afterUrl;
	}
}
